<?php

namespace app\api\controller\paotui\poster;

use addons\paotui\library\PosterToken;
use app\admin\model\paotui\PosterExtractType;
use app\common\library\Sms;
use think\Validate;
use think\Db;

/**
 * 骑手订单接口
 */
class Order extends PosterApi
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
	/**
     * 获取驿站及下订单数
     * @ApiMethod (POST)
     * 
     */
    public function get_school_station(){
        
        $work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
        $station = Db::name('station')->whereNull('deletetime')->where('school',$work['school'])->select();
		foreach($station as $k=>&$v){
			$pids=Db::name('partition')->where('station_id',$v['id'])->column('id');
			// $v['onum']=Db::name('paotui_post')->where('type',2)->where('from_address_id',$v['id'])->where('status',1)->count();
			$v['onum']=Db::name('partition_code')->where('status','0')->where('canceltime',0)->where(['school'=>$work['school']])->where('partition_id','in',$pids)->count();
		}
		
		$where=['status'=>['in','1,2'],'school'=>$work['school'],'take_user_id'=>$this->auth->id,'taketime'=>['between',[strtotime(date("y-m-d",time())),strtotime(date("y-m-d",time()))+86400]]];
		$num=Db::name('partition_code')->where('canceltime',0)->where('status',1)->where($where)->count();
		//今日收入计算
		//判断取件人员类型
		
		if($work['poster_type'] == 1){
		    //根据订单数算
		    $sum = Db::name('paotui_poster_money_log')->where(['poster_id'=>$this->auth->id])->where(['createtime'=>['between',[strtotime(date("y-m-d",time())),strtotime(date("y-m-d",time()))+86400]]])->sum('money');
		  //  $sum = $num*$work['brokerage_scale'];
		}else{
		    //获取今天的在线时间
		    $worktime = Db::name('worktime')->where(['createtime'=>['between',[strtotime(date("y-m-d",time())),strtotime(date("y-m-d",time()))+86400]]])->where('endtime is not null')->select();
		     
		    $alltime = 0;
		    if($worktime){
		        foreach($worktime as $kk=>$vv){
		            $alltime = $alltime + $vv['endtime'] - $vv['createtime'];
		        }
		    }
		    
		    $alltime = $alltime/3600;
		    
		    $sum = $work['brokerage_scale']*$alltime;
		    
		}
// 		$sum=Db::name('partition_code')->where($where)->sum('price');
		$dds=['todayCompleteNum'=>$num,'todayMoney'=>number_format($sum,2)];
		
		
		//运单号
		$ordernum =Db::name('paotui_post')->where('type',2)->where('note is not null')->where('status',0)->where('school',$work['school'])->where('is_delete',0)->count();
		
		//其他驿站
		$other=Db::name('partition_code')->where('status','0')->where('canceltime',0)->where(['school'=>$work['school']])->where('partition_id',0)->count();
		
		$station[] = [
		    'id'=>'other',
		    'name'=>'其他驿站',
		    'onum'=>$other
		   ];
		
// 		$station[] = [
// 		    'id'=>'ydh',
// 		    'name'=>'运单号',
// 		    'onum'=>$ordernum
// 		   ];
		
		
		$data=['lists'=>$station,'dds'=>$dds];
		
        $this->success('成功',$data);
    } 
	/**
     * 获取分区
     * @ApiMethod (POST)
     * 
     */
    public function get_partition(){
		$id=$this->request->param('id');
		if(!$id)$this->error('参数错误');
		$sts=Db::name('station')->whereNull('deletetime')->where('id',$id)->find();
		if(!$sts)$this->error('查无驿站');
        $partition = Db::name('partition')->where('station_id',$id)->select();
		foreach($partition as $k=>&$v){
			$v['onum']=Db::name('partition_code')->where('canceltime',0)->where('partition_id',$v['id'])->count();
		}
		
        $this->success('成功',$partition);
    } 
	/**
     * 获取分区取件码
     * @ApiMethod (POST)
     * 
     */
    public function get_partition_code(){
		$id=$this->request->param('id');
		if(!$id)$this->error('参数错误');
		$nowdate=date('Y-m-d');
		if($id == 'ydh'){
		    $work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
		    $pcode = Db::name('paotui_post')->where('type',2)->where('note is not null')->where('status',0)->where('school',$work['school'])->where('is_delete',0)->select();
		    
		    foreach($pcode as $k=>&$v){
                $userschool = Db::name('user_school')
					->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
    		    $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['codes'] = $v['note'];
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['name'];
                $v['to_nickname'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
    		    
    			$v['ctime']=date('Y-m-d H:i:s',$v['createtime']);
    			$v['allcode'] = 1;
    			$v['ydh']=1;
    		}
    	}else if($id == 'other'){
		    
    		$work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
            $pcode = Db::name('partition_code')->alias('a')->field("a.*,o.upstairs,o.valuable,o.to_address_id,o.appoints_day,s.house_number,o.createtime as ctime")
    			->join('paotui_post o','o.id=a.paotui_post_id','left')
    			->join('user_school s','s.id=o.to_address_id','left')
    			->where('a.partition_id',0)
    			->where('a.school',$work['school'])
    			->where('a.status','0')
    			->where('a.canceltime',0)
    			->order('o.valuable desc,a.codes asc,a.createtime')->select();
    		
    		// echo Db::name('partition_code')->getLastSql();
    		foreach($pcode as $k=>&$v){
                $userschool = Db::name('user_school')
					->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
    		    $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['name'];
                $v['to_nickname'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
    			$v['ctime']=date('Y-m-d H:i:s',$v['ctime']);
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
    			$v['allcode'] = Db::name('partition_code')->where(['paotui_post_id'=>$v['paotui_post_id']])->count();
    			$v['sycode'] = Db::name('partition_code')->where(['paotui_post_id'=>$v['paotui_post_id'],'status'=>0])->count();
    			
    		}
		}else{
		    $sts=Db::name('station')->where('id',$id)->find();
    		if(!$sts)$this->error('查无数据');
    		$ids=Db::name('partition')->where('station_id',$id)->column('id');
    		$work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
            $pcode = Db::name('partition_code')->alias('a')->field("a.*,o.upstairs,o.valuable,o.to_address_id,o.appoints_day,s.house_number,o.createtime as ctime")
    			->join('paotui_post o','o.id=a.paotui_post_id','left')
    			->join('user_school s','s.id=o.to_address_id','left')
    			->where('a.partition_id','in',$ids)
    			->where('a.school',$work['school'])
    			->where('a.status','0')
    			->where('a.canceltime',0)
    			->order('o.valuable desc,a.codes asc,a.createtime')->select();
    		
    		// echo Db::name('partition_code')->getLastSql();
    		foreach($pcode as $k=>&$v){
                $userschool = Db::name('user_school')
					->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
    		    $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['name'];
                $v['to_nickname'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
    		    
    			$v['ctime']=date('Y-m-d H:i:s',$v['ctime']);
    			$v['allcode'] = Db::name('partition_code')->where(['paotui_post_id'=>$v['paotui_post_id']])->count();
    			$v['sycode'] = Db::name('partition_code')->where(['paotui_post_id'=>$v['paotui_post_id'],'status'=>0])->count();
    			
    		}
		}
	
		
        $this->success('成功',$pcode);
    } 
    public function stoporder(){
        $id=$this->request->param('id');
        $res = Db::name('paotui_post')->where(['id'=>$id])->find();
        if(!$res){
            $this->error('订单获取失败');
        }
        $res = Db::name('paotui_post')->where(['id'=>$id])->update(['updatetime'=>time(),'status'=>5,'pay_status'=>1]);
        if($res){
            $this->success('成功');
        }else{
            $this->success('失败');
        }
    }
    /**
     * 今日已完成取件码
     * @ApiMethod (POST)
     * 
     */
    public function get_partition_code_today(){
	
		
		$nowdate=date('Y-m-d');
        $pcode = Db::name('partition_code')->alias('a')->field("a.*,o.upstairs,o.valuable,o.to_address_id,s.house_number,o.createtime as ctime")
			->join('paotui_post o','o.id=a.paotui_post_id','left')
			->join('user_school s','s.id=o.to_address_id','left')
			->where(['take_user_id'=>$this->auth->id])
			->where(['a.taketime'=>['gt',strtotime(date('Y-m-d',strtotime('-1 day')))]])
			->where('a.status',['in','1,2'])
			->where('a.canceltime',0)
			->order('a.taketime desc')->select();
	
		// echo Db::name('partition_code')->getLastSql();
		foreach($pcode as $k=>&$v){
            $userschool = Db::name('user_school')
					->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
		    $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
            $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
            $v['to_district'] = $school['name'];
            $v['to_poi'] = $building['name'];
            $v['to_address'] = $userschool['house_number'];
            $v['to_name'] = $userschool['name'];
            $v['to_nickname'] = $userschool['nickname'];
            $v['to_mobile'] = $userschool['phone'];
			$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
		    
			$v['ctime']=date('Y-m-d H:i:s',$v['ctime']);
			$v['taketime']=date('Y-m-d H:i:s',$v['taketime']);
		}
		
        $this->success('成功',$pcode);
    } 
    
	/**
     * 设置价格
     * @ApiMethod (POST)
     * 
     */
    public function doprice(){
        //判断人员是否听单中
        // $work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
        // if($work['is_order'] == 0){
        //     $this->error('请先听单');
        // }
		$id=$this->request->param('id');
		$price=$this->request->param('price');
		$takeimage=$this->request->param('takeimage');
		if(!$id || !$price || !$takeimage)$this->error('参数错误');
		if($price<=0){
		    $this->error('请填写正确的价格');
		}
		$sts=Db::name('partition_code')->where('id',$id)->where('canceltime',0)->find();
		if(!$sts)$this->error('查无数据');
// 		if($sts['status']!=0)$this->error('状态不可设置');
		$uparr=[
			'id'=>$id,
			'price'=>$price,
			'takeimage'=>$takeimage,
			'take_user_id'=>$this->auth->id,
			'taketime'=>time(),
			'status'=>'1',
			'error_type'=>0,
		];
		$res=Db::name('partition_code')->update($uparr);
		
		
		//首单判断 masks
		$data = Db::name('paotui_post')->where(['id'=>$sts['paotui_post_id']])->find();
		$type=$data['type'];
		$issd=0;
		$is1=Db::name('paotui_post')->where(['user_id'=>$data['user_id'],'type'=>$type])->order('createtime')->find();
		// echo Db::name('paotui_post')->getLastSql();
		if($is1['id']==$data['id']){
// 			$issd = 1;
		}
		$pp=$price;
		if($issd)$pp=0;
		
		//价格添加到订单中
		$pt_order = Db::name('paotui_post')->where(['id'=>$sts['paotui_post_id']])->find();
		$allcode = Db::name('partition_code')->where('canceltime',0)->where(['paotui_post_id'=>$sts['paotui_post_id']])->where(['status'=>0])->find();
		if($sts['status']!=0){
		    $pt_order['total_price'] = $pt_order['total_price'] - $sts['price'];
		    if($pt_order['pay_price']>=$sts['price']&&$pt_order['pay_price']>0){
		        $pt_order['pay_price'] = $pt_order['pay_price'] - $sts['price'];
		    }
		    
		}
		$data= [
		    'id'=>$pt_order['id'],
		    'total_price'=>$pt_order['total_price'] + $price,
		    'pay_price'=>$pt_order['pay_price'] + $pp,
		    'updatetime'=>time()
		    ];
// 		if($pt_order['images']){
// 		    $data['images'] .= $pt_order['images'].','.$takeimage;
// 		}else{
// 		    $data['images'] = $takeimage;
// 		}
		if(!$allcode){
		    //如果存在allcode
		    if($sts['price'] == 0){
		        $data['status'] = 2;
		    }
		}
		$rx = Db::name('paotui_post')->update($data);
		
		if($res){
		    //取件成功判断工作人员类型
		    $poster = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
		    if($poster['poster_type'] == 1){
		        //按个数计件
		        $price = $poster['money'] + $poster['brokerage_scale'];
		        Db::name('paotui_poster')->where(['id'=>$this->auth->id])->update(['money'=>$price,'updatetime'=>time()]);
		        //生成资金记录
		        $data = [
		            'poster_id'=>$this->auth->id,
		            'type'=>'order',
		            'source_id'=>$pt_order['id'],
		            'money'=>$poster['brokerage_scale'],
		            'before'=>$poster['money'],
		            'after'=>$price,
		            'memo'=>'取件分佣',
		            'createtime'=>time()
		        ];
		        $recorde = Db::name('paotui_poster_money_log')->insert($data);   
		        
		    }
		    //生成一条记录
		    $logdata = [
		        'post_id'=>$pt_order['id'],
		        'poster_id'=>$this->auth->id,
		        'poster_name'=>$poster['poster_name'],
		        'poster_mobile'=>$poster['mobile'],
		        'type'=>5,
		        'createtime'=>time(),
		        ];
		    $addlog = Db::name('paotui_post_order')->insert($logdata);      
			$this->success('成功');
		}else{
			$this->error('失败');
		}
    } 
	/**
     * 获取驿站订单
     * @ApiMethod (POST)
     * 
     */
    public function get_station_order(){
		$id=$this->request->param('id');
		$page=$this->request->param('page');
		if(!$id)$this->error('参数错误');
		$sts=Db::name('station')->whereNull('deletetime')->where('id',$id)->find();
		if(!$sts)$this->error('查无驿站');
		$ev=10;
		$limit=$page*$ev.','.$ev;
		$res=Db::name('paotui_post')->where('type',2)->where('from_address_id',$id)->where('status',1)->limit($limit)->order('createtime desc')->select();
		// echo Db::name('paotui_post')->getLastSql();
		foreach($res as $k=>&$v){
			
            if($v['type'] == 2){
                $station = Db::name('station')->where(['id'=>$v['from_address_id']])->where('deletetime is null')->find();
                $school = Db::name('school')->where(['id'=>$station['school']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $station['name'];
                $v['from_address'] = $station['address'];
                $v['from_name'] = $station['name'];
                $v['from_mobile'] = '';
                
                //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
                //取件码
                $codes  = Db::name('partition_code')->where(['paotui_post_id'=>$v['id']])->where('canceltime',0)->select();
                $codearr = [];
                foreach($codes as $kk=>$vv){
                    //取件码分组
                    $partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
                    $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                    //整理取件码
                    $data2 = [
                        'partition_name'=>$partition['name'],
                        'code'=>$vv['codes'],
                    ];
                    
                    $codearr[$station['id']]['data'][] =  $data2;
                    $codearr[$station['id']]['name'] = $station['name'];
                }
                $v['codearr'] = $codearr;
			}
		}
		
        $this->success('成功',$res);
    } 
}
